package com.yaodian100.ec.generate.service.impl;

import java.io.File;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.io.FileUtils;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.ec.generate.entity.ViewPromotionAdvertise;

public class Top4TagGenerater extends AbstractAdvGenerater {

	public static final String ADV_TYPE_TOP4_TAG = "TOP4_TAG";

	private final GenerateServiceImpl generateServiceImpl;

	Top4TagGenerater(GenerateServiceImpl impl) {
		this.generateServiceImpl = impl;
	}

	public boolean generateTop4Tag() throws Exception {
		String advType = ADV_TYPE_TOP4_TAG;

		List<Long> activeAdvIdList = new ArrayList<Long>();

		CommonCriteria criteria = new CommonCriteria();
		criteria.addEq("advType", advType);

		List<ViewPromotionAdvertise> viewPromotionAdvs = this.generateServiceImpl.getViewPromotionAdvertiseDao()
				.getListPageable(criteria, new String[] { "showSeq asc", "startDate", "advTarget" }, 0, -1);
		if (viewPromotionAdvs != null) {

			this.generateServiceImpl.deleteFiles(ServerValue.getFrontApachePath() + File.separator + "pages" + File.separator
					+ "header", advType);

			for (ViewPromotionAdvertise viewPromotionAdv : viewPromotionAdvs) {
				int index = viewPromotionAdvs.indexOf(viewPromotionAdv);
				if (index > 2) {
					break;
				}

				Reader reader = null;
				Properties prop = null;

				prop = new Properties();
				reader = new StringReader(viewPromotionAdv.getContents());
				prop.load(reader);
				reader.close();

				prop.put("advType", advType);

				Map<String, Object> m = new HashMap<String, Object>();
				m.put("prop", prop);

				StringBuilder htmlFilePath = new StringBuilder();
				htmlFilePath.append(ServerValue.getFrontApachePath());
				htmlFilePath.append(File.separator);
				htmlFilePath.append("pages");
				htmlFilePath.append(File.separator);
				htmlFilePath.append("header");
				htmlFilePath.append(File.separator);
				htmlFilePath.append(advType + "_" + String.valueOf(index + 1));
				htmlFilePath.append(".html");
				FileUtils.writeStringToFile(new File(htmlFilePath.toString()), generateServiceImpl.getTemplateService().format(
						"static_Top4Tag", m).replaceAll("http://www.yaodian100.com", ""));

				activeAdvIdList.add(Long.valueOf(viewPromotionAdv.getId()));
			}
		}

		this.generateServiceImpl.updateAdvStatus(advType, activeAdvIdList);
		return true;
	}
}